package tk.kikt

import org.json.JSONObject
import tk.kikt.ext.toJson
import tk.kikt.req.LoginRequest

import java.io.*
import java.net.Socket

object ClientTest {

    @Throws(IOException::class)
    @JvmStatic fun main(args: Array<String>) {
        val socket = Socket("localhost", 10100)
        out(socket)
        `in`(socket)

        writeSystemIn(socket)
    }

    private fun writeSystemIn(socket: Socket) {
        object : Thread() {
            override fun run() {
                super.run()
                val writer: BufferedWriter
                try {
                    writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream()))
                } catch (e: IOException) {
                    return
                }

                val reader = BufferedReader(InputStreamReader(System.`in`))

                while (true) {
                    try {
                        val s = reader.readLine()
                        writer.write(s + "\n")
                        writer.flush()
                    } catch (e: IOException) {
                        e.printStackTrace()
                        break
                    }

                }
            }
        }.start()
    }

    private fun `in`(socket: Socket) {
        object : Thread() {
            override fun run() {
                super.run()
                try {
                    val `is` = socket.getInputStream()
                    val buf = ByteArray(1024)
                    while (true) {
                        val len = `is`.read(buf)
                        if (len <= 0) {
                            continue
                        }
                        val s = String(buf, 0, len)
                        println("rec : " + s)
                        if ("exit" == s) {
                            break
                        }
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }.start()
    }

    private fun out(socket: Socket) {
        object : Thread() {
            override fun run() {
                super.run()
                try {
                    val os = socket.getOutputStream()
                    for (i in 0..4) {
                        os.write(getSendMsg(2).toByteArray())
                        os.flush()
                        println("hello:" + i)
                        Thread.sleep(1000)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

            }
        }.start()
    }

    private fun getSendMsg(i: Int): String {
        val request = LoginRequest()
        request.userName = "admin"
        request.pwd = "pwd"

        return request.toJson()
    }

    private class Bean {

        var needUser: Int = 0
    }
}
